# -*- coding: UTF-8 -*-
from functools import wraps
from flask import request
from flask import jsonify
import log_helper
import logging

logger = logging.getLogger('lte')

def api_call(fn):
    """
    封装结果
    :param fn:
    :return:
    """

    @wraps(fn)
    def wrapper(*args, **kwargs):
        """
        :param args:
        :param kwargs:
        :return:
        """
        status_code = 0
        msg = '操作成功'
        result = None
        try:
            result = fn(*args, **kwargs)
        except Exception as e:
            logger.error(log_helper.format_exc_all())
            msg = '发生了错误:' + str(e.message)
            status_code = 1
        if request:
            if not result:
                result = {}
            try:
                if result and '_status' in result:
                    status_code = result['_status']
                    del result['_status']
                if result and '_msg' in result:
                    msg = result['_msg']
                    del result['_msg']
            except TypeError:
                pass
        if status_code == 0:
            return jsonify(code=status_code, msg=msg, count=0, data=result)
        else:
            return jsonify(code=status_code, msg=msg, count=0, data={})

    return wrapper
